package com.rapid.maintenance.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatEditText;

import com.blankj.utilcode.util.SizeUtils;

/**
 *
 */
public class DrawableClickableEditView extends AppCompatEditText {

    private Drawable mClearDrawable;
    private OnDrawableClickListener onDrawableClick;

    /**
     * @param context context
     */
    public DrawableClickableEditView(Context context) {
        super(context);
        init(context);
    }

    /**
     * @param context context
     * @param attrs   attrs
     */
    public DrawableClickableEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * @param context  context
     * @param attrs    attrs
     * @param defStyle defStyle
     */
    public DrawableClickableEditView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }


    private void init(Context context) {
        final int PADDING_RIGHT = SizeUtils.dp2px(6);
        final int PADDING_TOP = SizeUtils.dp2px(4);

        mClearDrawable = getCompoundDrawables()[2];
        if (mClearDrawable == null) return;
        mClearDrawable.setBounds(-PADDING_RIGHT, PADDING_TOP
                , mClearDrawable.getIntrinsicWidth() - PADDING_RIGHT
                , mClearDrawable.getIntrinsicHeight() + PADDING_TOP);
    }

    public void setOnDrawableClick(OnDrawableClickListener onDrawableClick) {
        this.onDrawableClick = onDrawableClick;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {

                boolean isClearButtonClicked = event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < ((getWidth() - getPaddingRight())));

                if (isClearButtonClicked) {
                    if (onDrawableClick != null) onDrawableClick.onClick();
                }
            }
        }

        return super.onTouchEvent(event);
    }

    private void setClearIconVisible(boolean visible) {
        Drawable right = visible ? mClearDrawable : null;
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }

    public interface OnDrawableClickListener {
        void onClick();
    }
}
